import { getListApi, getPageStaticApi } from "@/api/client/documentManagement/advanceManagement";
import { printLabelApi } from "@/api/common";
import CommonHook from "@/hook/commonHook";
import printJs from "print-js";
import { message as Message } from "ant-design-vue";
import { computed } from "vue";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableData, drawerOpts, loading, activeKey, pageStat, tableRef } = state;
  const { getNoZeroKey, downloadFileByBlob } = CommonHook();
  const selectRows = computed<Array<ClientAdvanceManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = async () => {
    const params = {
      ...getParams(),
      statusList: activeKey.value === "0" ? [0, 1, 2] : [3]
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        pageStat.value[0] = data["0"] || 0;
        pageStat.value[1] = data["1"] || 0;
        activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1"]));
      }
    });
  };
  const getParams = () => {
    const { preOrderNoList, waybillNumList, pageNum, pageSize } = searchForm;
    const params: any = {
      preOrderNoList: [],
      waybillNumList: [],
      pageNum,
      pageSize
    };
    if (preOrderNoList)
      params.preOrderNoList = preOrderNoList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  const editHandle = (row: ClientAdvanceManagement.ListRows) => {
    drawerOpts.title = `编辑(${row.preOrderNo})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const showHandle = (row: ClientAdvanceManagement.ListRows) => {
    drawerOpts.title = `查看(${row.preOrderNo})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const cancelHandle = (row: ClientAdvanceManagement.ListRows) => {
    drawerOpts.title = `取消预报(${row.preOrderNo})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "CancelAdvance";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 打印
  const printLabelHandle = (row: ClientAdvanceManagement.ListRows) => {
    loading.value = true;
    printLabelApi({ idList: [row.id], type: 1 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };
  // 下载标签  2合并标签
  const downloadLabelHandle = (row: ClientAdvanceManagement.ListRows | undefined, buttonType: number | undefined) => {
    if (!selectRows.value.length && !row) return Message.error("请勾选运单!");

    loading.value = true;
    const idList = row ? [row.id] : selectRows.value.map(({ id }) => id);

    printLabelApi({ idList, type: 1, buttonType })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          //判断推单状态
          if (res.headers["content-type"] === "application/pdf") {
            if (selectRows.value.length) {
              const { preOrderNo, totalItemNumber } = selectRows.value[0];
              downloadFileByBlob(res.data, `${preOrderNo}+${totalItemNumber}件.pdf`, "application/pdf");
            } else {
              downloadFileByBlob(res.data, `${row?.preOrderNo}+${row?.totalItemNumber}件.pdf`, "application/pdf");
            }
          } else {
            downloadFileByBlob(res.data, "预报单.zip");
          }
        }
      })
      .finally(() => (loading.value = false));
  };

  return {
    searchHandle,
    getData,
    editHandle,
    showHandle,
    changeTabHandle,
    cancelHandle,
    pageStateic,
    printLabelHandle,
    downloadLabelHandle
  };
}
